window.onload=function() {
	// test	
	 
	document.getElementById('files').addEventListener('change', handleFileSelect, false);	
	
	im = new Image(); 
	im.src = "/images/2.jpg";
	//Event
	canvas = document.getElementById('canvas');
	c2 = document.getElementById('canvas2');
	ctx2 = c2.getContext('2d');
	isDown = false;
	
	im.onload = function () { 
		drawTrails();
		c2.width = width;
		c2.height = height;
	}
	canvas.onselectstart = function () { return false; } 
	canvas.onmousedown = function() {
			//TODO: Debug
			ctx2.drawImage(canvas, 0, 0);
			//--TODO

		isDown = true;
		mx = [];
	}
	canvas.onmouseup = function(e) {
		//ctx.globalAlpha = 0.5;
		isDown = false;
		
		if (instrument == 1 && mx.length > 0)
			{
			connect(mx[0].x, mx[0].y, mx[mx.length-1].x,mx[mx.length-1].y);
			
			ctx.drawImage(c2, 0, 0);			
			drawSelection();
			interpolation();
		}
		if (instrument == 2)
		{
			drawCircle(e);
		}
	}
	canvas.onmousemove =function(e)
	{
		if (instrument == 1)
		{
			selection();
		}
		else
		{
			drawCircle(e)
		};
	}
}

function drawCircle(e)
{
	if (isDown == false)
	{
		return;
	};
			var x;
			var y;
			if (e.pageX || e.pageY) { 
			  x = e.pageX;
			  y = e.pageY;
			}
			else { 
			  x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; 
			  y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; 
			} 
			x -= canvas.offsetLeft;
			y -= canvas.offsetTop;
			center.x = x;
			center.y = y;
						
			drawSelection();
			interpolation();
}

var instrument = 2;
var center =
{
	x:200,
	y:200
};

var colorsR = {};
var colorsG= {};
var colorsB = {};

var c2
var canvas;
var ctx;
var ctx2 ;
var im;
var isDown;
var s;
var height;
var width;
var insidePix;

var red;
var green;
var blue;

var imageData;
var r = 0;
var g = 0;
var b = 0;
var len = 0;

function connect(x1,y1, x2, y2)
{
	ctx.strokeStyle = "Green";
	if(x1!= x2 || y1 != y2)
		{
			ctx.beginPath();
			ctx.moveTo(x1,y1);
			ctx.lineTo(x2,y2);
			ctx.closePath();
			ctx.stroke();
		}
		
}
function selection(e)
{
	//ctx.fillStyle = "Blue";
	if(isDown)
	{
		var x;
		var y;
		if (e.pageX || e.pageY) { 
		  x = e.pageX;
		  y = e.pageY;
		}
		else { 
		  x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; 
		  y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; 
		} 
		x -= canvas.offsetLeft;
		y -= canvas.offsetTop;
		mx.push({x: x, y : y});
		if (mx.length > 1)
		{
			connect(x, y, mx[mx.length-2].x, mx[mx.length-2].y);
		}
	}	
}

function newStatus2(y, x)
{
	if (s != null && x < s.minx)
	{
		if(s.inside)
		{ 
			len++;
		}
	}
	else
	{		
		var min = 100000;
		var nvert = mx.length;
		var testx = x, testy = y;
		var c = false;
		for (i = 0, j = nvert-1; i < nvert; j = i++) {
		if ( ((mx[i].y>testy) != (mx[j].y>testy)) &&
		 (testx < (mx[j].x-mx[i].x) * (testy-mx[i].y) / (mx[j].y-mx[i].y) + mx[i].x) )
		    {
				
				var dx = (mx[j].x-mx[i].x) * (testy-mx[i].y) / (mx[j].y-mx[i].y) + mx[i].x;				

				dx = Math.floor(dx);
				if (dx > x) {
					c = !c;
				}
				
				if(dx > x && dx < min)
					{		
						
						min = dx;
					}
			}			
		}
		if (min !=100000)
			{
				
				if (s == null) {
					s = {
						minx: min,
						inside: c//false
					};
				} else {
					s.minx = min;
					s.inside = c;
				}
				if (s.inside)
				{
					len ++;
				}
			}			
			else
			{
				s = null;
				return false;
			}		
	}
	return true;	
}

function processPoint(i,j,minx)
{
	var b ;
	if (instrument == 1){
		b = calcAlpha(j,i);
	}
	else{
		var cy = Math.abs(center.y - i);
		var cx = Math.abs(center.x - j);
		b = 25 - dest(center.x,center.y,j,i);
	}
	insidePix.push({x:j, y:i, minBord: b});
	r+=(imageData.data[(width *i +j)*4]);
	g+=(imageData.data[(width *i +j)*4+1]);
	b+=(imageData.data[(width *i +j)*4+2]);
	colorsR[imageData.data[(width *i +j)*4]]++;
	colorsG[imageData.data[(width *i +j)*4+1]]++;
	colorsB[imageData.data[(width *i +j)*4+2]]++;
}

function drawSelection()
{
	insidePix = [];
	
	for (var i = 0;  i < 256; i ++) 
	{
		colorsR[i]=0;
		colorsG[i]=0;
		colorsB[i] =0;
	}
	if (instrument ==1)
	{for (var i = 0; n = height, i < n; i ++) 
	{
		for (var j = 0; m = width, j < m; j ++)
		{
			if (!newStatus2(i,j))
			 {
				if (s!= null && s.inside)
				{
					processPoint(i,j,s.minx);
					
				}
				 break;
			}
			if (s!= null && s.inside)
			{
				processPoint(i,j, s.minx);
			}
						
		}
	}
	}
	if (instrument == 2)
	{
		for (var i = center.x-25 ; i < center.x+ 25; i++)
		{
			
			for (var j = center.y-25; j < center.y+25; j++)
			{
				if ((i- center.x)*(i- center.x) + (j- center.y)*(j- center.y) < 625)
				{
					processPoint(j,i,0);
					len++;
				}
			}
		}
	}
	
	red =Math.round(r/len);
	green = Math.round(g/len);
	blue = Math.round(b/len);
	
	
	var maxR,maxG,maxB =0;
	for (var i = 0;  i < 256; i ++) 
	{
		if(maxR<colorsR[i])
		{
			maxR = colorsR[i];
			red = i;
		}
		if(maxG<colorsG[i])
		{
			maxG = colorsG[i];
			green= i;
		}
		if(maxB<colorsB[i])
		{
			maxB = colorsB[i];
			blue = i;
		}
		
	}
	
	
	imageData = ctx.getImageData(0, 0, width, height);

	r = 0;
	g= 0;
	b = 0;
	len = 0;
}

function calcAlpha(x,y)
{
	var min = 100000;
	for(var k=0; k < mx.length; k++)
	{
		if (min > dest(x,y,mx[k].x,mx[k].y))
		{
			min = dest(x,y,mx[k].x,mx[k].y);
		}
	}
	var h = Math.abs((mx[0].x - x)*(mx[mx.length-1].y - y)-  (mx[0].y - y)*(mx[mx.length-1].x - x) )/
		(dest(mx[0].x, mx[0].y,mx[mx.length-1].x, mx[mx.length-1].y));
	if (min > h)
		{
			min = h;
		}
	return min;
}
function dest(i1,j1,i2,j2)
{
	return Math.sqrt((i1-i2)*(i1-i2) + (j1-j2)*(j1-j2))
}
function interpolation ()
	{
		var  k = 0;
		for (var i = 0; i< insidePix.length; i++)
		{
			
			if (k < insidePix[i].minBord)
			{
				k = insidePix[i].minBord;
			}
		}
		
		for (var i = 0; i< insidePix.length; i++)
		{
			var x = insidePix[i].x;
			var y = insidePix[i].y;
			var r1=(imageData.data[(width *y +x)*4]);
			var g1=(imageData.data[(width *y +x)*4+1]);
			var b1=(imageData.data[(width *y +x)*4+2]);
			
			var kr = Math.abs(red- r1)/255;			
			var kg = Math.abs(green- g1)/255;			
			var kb = Math.abs(blue- b1)/255;			
		
			kr = Math.min(kr+1,1)	;
			kg = Math.min(kg+1,1);
			kb = Math.min(kb+1,1);
			
			
			var r2 = Math.round((kr*red+(1-kr)*r1));						
			var g2 = Math.round((kg*green+(1-kg)*g1));
			var b2 = Math.round((kb*blue+(1-kb)*b1));			
			
			ctx.globalAlpha = Math.min((insidePix[i].minBord/k),1);
			ctx.fillStyle =  'rgb(' +r2+ ',' +g2+ ',' +b2+ ')';
			ctx.fillRect (x, y, 1, 1);
			
			
			
		}
		ctx.globalAlpha = 1;
	}
	



